/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * 后序递归，从下层往上层返回节点
 * @param {TreeNode} root
 * @param {number} low
 * @param {number} high
 * @return {TreeNode}
 */
var trimBST = function (root, low, high) {
    return trimBSTLevel(root, low, high)
};

function trimBSTLevel(root, low, high) {
    if (root === null) return null

    if (root.val < low) {
        root.left = null
    } else {
        root.left = trimBSTLevel(root.left, low, high)
    }
    if (root.val > high) {
        root.right = null
    } else {
        root.right = trimBSTLevel(root.right, low, high)
    }

    if (root.val > high || root.val < low) {
        if (root.right === null && root.left === null) {
            return null
        } else if (root.right !== null && root.left === null) {
            return root.right
        } else if (root.right === null && root.left !== null) {
            return root.left
        } else {
            let temp = root.right
            while (temp.left !== null) {
                temp = temp.left
            }
            temp.left = root.left
            return root.right
        }
    }

    return root
}



/**
 * 递归-官解
 * @param {TreeNode} root
 * @param {number} low
 * @param {number} high
 * @return {TreeNode}
 */
var trimBST = function (root, low, high) {
    return trimBSTLevel(root, low, high)
};

function trimBSTLevel(root, low, high) {
    if (root === null) return null

    if (root.val < low) {
        return trimBSTLevel(root.right, low, high)
    } else if (root.val > high) {
        return trimBSTLevel(root.left, low, high)
    } else {
        root.left = trimBSTLevel(root.left, low, high)
        root.right = trimBSTLevel(root.right, low, high)
        return root
    }
}